package queries;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import connect.DBConnectionUtil;

public class Query4 extends JFrame{
	public Query4(){
		this.setBounds(300,240,500,300);
		this.setLayout(null);
		JLabel label0 = new JLabel("Enter patientid to delete patient");
		label0.setBounds(200, 10, 500, 30);
		this.add(label0);
		JLabel label1 = new JLabel("Pid:");
		JTextField pid = new JTextField();
		label1.setBounds(100, 50, 100, 30);
		pid.setBounds(200, 50, 200, 30);
		this.add(label1);
		this.add(pid);
		
		
		JButton delete = new JButton("Delete");
		delete.setBounds(200, 100, 100, 30);
		this.add(delete);
		this.setTitle("Query4:Delete patient");
		this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		
		this.setVisible(true);
		delete.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent arg0) {
				try {
					// 1.connect database
					Class.forName(DBConnectionUtil.DBDRIVER).newInstance();
					Connection con = DBConnectionUtil.getConnection();
					if(con!=null){
						System.out.println("Connect database successfully!");
					}
					PreparedStatement ps = con
							.prepareStatement("SELECT  * FROM Patient WHERE pid=?");
					ps.setInt(1, Integer.parseInt(pid.getText()));
					ResultSet rset = ps.executeQuery();
					if (!rset.next()) {
						JOptionPane.showMessageDialog(null,
								"Pid does not exsit!");
						return;
					}
					// 2.query code
					 ps = con
							.prepareStatement("DELETE FROM Patient WHERE pid = ?");
					ps.setString(1, pid.getText());
					ps.executeQuery();

					JOptionPane.showMessageDialog(null, "Delete Patient Info Successfully!");
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			
		});
		
	}
}
